package com.example.blue;


import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class BindActivity extends AppCompatActivity {

    private static final String TAG = "BindActivity";
    private TextView tvDeviceInfo;
    private Button magButton, tuoButton, testButton,oulaButton;

    private String deviceId;
    private String deviceMacLeft;
    private String deviceMacRight;
    private BluetoothService bluetoothService;
    private boolean isServiceBound = false;
    private Integer conDeviceNum=1;
    private Integer handDir=0;

    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            BluetoothService.LocalBinder binder = (BluetoothService.LocalBinder) service;
            bluetoothService = binder.getService();
            isServiceBound = true;
            // 可以进行一些初始化操作，例如设置UI状态
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            isServiceBound = false;
        }
    };
//    private final BroadcastReceiver bleReceiver = new BroadcastReceiver() {
//        @Override
//        public void onReceive(Context context, Intent intent) {
//            String action = intent.getAction();
//            if (BluetoothService.ACTION_CONNECTED.equals(action)) {
//                Toast.makeText(context, "蓝牙已连接", Toast.LENGTH_SHORT).show();
//            } else if (BluetoothService.ACTION_DISCONNECTED.equals(action)) {
//                Toast.makeText(context, "蓝牙已断开", Toast.LENGTH_SHORT).show();
//            } else if (BluetoothService.ACTION_DATA_AVAILABLE.equals(action)) {
//                Toast.makeText(context, "蓝牙收到数据", Toast.LENGTH_SHORT).show();
//            }
//        }
//    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        CrashHandler.getInstance().init(this);
        setContentView(R.layout.activity_bind);
        // 开启返回箭头
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeAsUpIndicator(null);
        getSupportActionBar().setTitle("连接设备");

        SharedPreferences sp = getSharedPreferences("my_cache", Context.MODE_PRIVATE);
        conDeviceNum = sp.getInt("conDeviceNum", 1);
        if(conDeviceNum==1) {
            handDir = sp.getInt("handDirection",0);
            if(handDir==1){
                deviceId = sp.getString("DEVICE_ADDRESS_LEFT", "");
            }else{
                deviceId = sp.getString("DEVICE_ADDRESS_RIGHT", "");
            }

        }
        if(conDeviceNum==2){
            deviceMacLeft = sp.getString("DEVICE_ADDRESS_LEFT","");
            deviceMacRight=sp.getString("DEVICE_ADDRESS_RIGHT","");
            System.out.println("magcor----deviceMacLeft:"+deviceMacLeft);
            System.out.println("magcor----deviceMacRight:"+deviceMacRight);
//            if (deviceMacLeft == null || deviceMacLeft.isEmpty() || deviceMacRight == null || deviceMacRight.isEmpty()) {
//                Toast.makeText(BindActivity.this, "未获取到蓝牙MAC地址，请重新连接", Toast.LENGTH_SHORT).show();
//            }

        }
        // 初始化视图
        initViews();

        // 显示设备信息
        tvDeviceInfo.setText(deviceId);
        // 设置按钮点击监听器
        magButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent magInt = new Intent(BindActivity.this, MagCorActivity.class);
                startActivity(magInt);

            }
        });

        tuoButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(BindActivity.this, TuoCorActivity.class);
                startActivity(intent);
            }
        });

        testButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(BindActivity.this, TestActivity.class);
                startActivity(intent);
            }
        });
        oulaButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(BindActivity.this, OulajiaoActivity.class);
                startActivity(intent);
            }
        });
    }
    @Override
    protected void onStart() {
        super.onStart();
        if(conDeviceNum==1) {
            if(handDir==1) {
                Intent intent = new Intent(this, BluetoothService.class);
                intent.putExtra("DEVICE_ADDRESS_LEFT", deviceId);
                bindService(intent, connection, Context.BIND_AUTO_CREATE);
            }else{
                Intent intent = new Intent(this, BluetoothService.class);
                intent.putExtra("DEVICE_ADDRESS_RIGHT", deviceId);
                bindService(intent, connection, Context.BIND_AUTO_CREATE);
            }
        }
        if(conDeviceNum==2) {
            Intent intent = new Intent(this, BluetoothService.class);
            intent.putExtra("DEVICE_ADDRESS_LEFT", deviceMacLeft);
            intent.putExtra("DEVICE_ADDRESS_RIGHT", deviceMacRight); // 如果需要
            bindService(intent, connection, Context.BIND_AUTO_CREATE);
        }
    }
    @Override
    protected void onResume() {
        super.onResume();
//        IntentFilter filter = new IntentFilter();
//        filter.addAction(BluetoothService.ACTION_CONNECTED);
//        filter.addAction(BluetoothService.ACTION_DISCONNECTED);
//        filter.addAction(BluetoothService.ACTION_DATA_AVAILABLE);
//        filter.addAction(BluetoothDevice.ACTION_FOUND);
//        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { // API 33+
//            registerReceiver(bleReceiver, filter, Context.RECEIVER_NOT_EXPORTED);
//        } else {
//            registerReceiver(bleReceiver, filter);
//        }
    }

    // 处理返回箭头点击事件
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish(); // 结束当前Activity，返回上一个
            return true;
        }
        return super.onOptionsItemSelected(item);
    }


    private void initViews() {
        tvDeviceInfo = findViewById(R.id.tvDeviceInfo);
        magButton = findViewById(R.id.magCorrect);
        tuoButton = findViewById(R.id.tuoluoCorrect);
        testButton = findViewById(R.id.funTest);
        oulaButton = findViewById(R.id.oulajiao);
        magButton.setBackgroundColor(Color.parseColor("#1E90FF")); // 使用十六进制颜色值
        tuoButton.setBackgroundColor(Color.parseColor("#1E90FF")); // 使用十六进制颜色值
        testButton.setBackgroundColor(Color.parseColor("#1E90FF")); // 使用十六进制颜色值
        oulaButton.setBackgroundColor(Color.parseColor("#1E90FF")); // 使用十六进制颜色值
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 100) {
            for (int i = 0; i < grantResults.length; i++) {
                if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(this, "需要权限: " + permissions[i], Toast.LENGTH_SHORT).show();
                    return;
                }
            }
        }
    }


    @Override
    protected void onStop() {
        super.onStop();
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}